package logic

import (
	"context"
	"fmt"
	"zhihu/models/cache"
	"zhihu/models/mysql"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码
func (l *UpdatePasswordLogic) UpdatePassword(in *zhihurpc.UpdatePasswordRequest) (*zhihurpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在，无法修改密码")
	}
	if in.NewPassword != in.AskPassword {
		return nil, fmt.Errorf("两次密码输入不一致，请重试")
	}

	sendSmsCode := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Val()
	if sendSmsCode != in.SendSmsCode {
		return nil, fmt.Errorf("验证码输入错误")
	}

	user.Password = pkg.Md5(in.NewPassword)
	mysql.DB.Debug().Updates(&user)
	return &zhihurpc.UpdatePasswordResponse{
		Id: int64(user.ID),
	}, nil
}
